import * as React from 'react';
import {runOnJS} from 'react-native-reanimated';

import { View, Text,Platform, TouchableWithoutFeedback,} from 'react-native';
import { useCameraDevices, useFrameProcessor, Camera} from 'react-native-vision-camera';
import {scanFaces, Face} from 'vision-camera-face-detector';
import {SafeAreaView} from 'react-native-safe-area-context';
import AllStyle from '../../../style';
import {Toast} from '../../../utils/Toast';
import {useRef} from 'react';
import {faceRecognitionPunch} from '../../../api/empRecords';
let faceWidthAndHeight=220;
if (Platform.OS === 'ios') {
    faceWidthAndHeight=220
}
if (Platform.OS === 'android') {
    faceWidthAndHeight=240
}

export function FaceRecognitionPunch(props) {
    const [hasPermission, setHasPermission] = React.useState(false);
    const [faces, setFaces] = React.useState([]);
    const [msg, setMsg] = React.useState(null);
    const [uploadMsg, setUploadMsg] = React.useState('人脸图像录入中');
    const [isActiveVal, setIsActiveVal] = React.useState(true);
    const camara=useRef(null)
    const devices = useCameraDevices();
    const device = devices.front;


    React.useEffect( () => {
        let facesArr = [];
        facesArr = faces;
        if (facesArr.length > 0) {
            let face = facesArr[0];
            if (JSON.stringify(face.contours) == '{}') {
                setMsg('人脸信息不全');
            } else {
                if (face.leftEyeOpenProbability == 1 && face.rightEyeOpenProbability == 1 && face.pitchAngle == 0 && face.rollAngle == 0) {
                    setMsg('面部遮挡');
                } else {
                    if (face.leftEyeOpenProbability < 0.8 && face.rightEyeOpenProbability < 0.8) {
                        setMsg('请睁眼');
                    } else {
                        if (!(Math.abs(face.pitchAngle) < 6 && Math.abs(face.rollAngle) < 6 && Math.abs(face.yawAngle) <= 6)) {
                            setMsg('请正面朝向屏幕');
                        } else {
                            setIsActiveVal(false);
                            takePicture().then(res=>{
                                console.log('成功',res)
                            }).catch()

                        }
                    }
                }
            }
        }


    }, [faces]);

    React.useEffect(() => {
        (async () => {
            const status = await Camera.requestCameraPermission();
            setHasPermission(status === 'authorized');
        })();
    }, []);

    const frameProcessor = useFrameProcessor((frame) => {
        'worklet';
        const scannedFaces = scanFaces(frame);
        //console.log(setFaces,'setFaces')
        runOnJS(setFaces)(scannedFaces);
    }, []);


    const  back = () => {
        const route = {
            name: props.route.params.routePathName,
            params: {
                title:'打卡'
            },
        };
        props.navigation.navigate(route);
    };
    const takePicture=async ()=>{
        if (camara.current) {
            let photo = null;
            if (Platform.OS === 'ios') {
                photo = await camara.current.takePhoto({
                    qualityPrioritization: 'speed',
                    flash: 'off',
                    enableAutoRedEyeReduction: true,
                });
            } else {
                photo = await camara.current.takeSnapshot({
                    quality: 80,
                    skipMetadata: true,
                });
            }
            setMsg(null);
            setUploadMsg('上传中,请等待结果')
           // setPhotoPath(photo.path)
            //打卡
            complete(photo.path)
            console.log('photo',photo.path)
        }
        


    }
    const complete=(path)=>{
        const data=new FormData();
        data.append('file',{
            uri: 'file://'+path,
            type: 'image/jpeg',
            name: 'photo.jpg',
        })
        data.append('equipment','待完善.....')
        data.append('recordsLongitude',props.route.params.recordsLongitude)
        data.append('recordsLatitude',props.route.params.recordsLatitude)
        //Loading.show();

        faceRecognitionPunch(data).then(res => {
            //Loading.hidden();
            Toast.showWarning('打卡成功');
           //返回
            back();
        }).catch(err => {
            //Loading.hidden();
            Toast.showWarning(err.toString());
            back();

        }).finally(()=>{
           // Loading.hidden();
            back();
        });


    }
    return device != null && hasPermission ? (
        <SafeAreaView edges={['top', 'left', 'right', 'bottom']} style={{flex: 1, backgroundColor: '#F1F0F5'}}>
            <View style={AllStyle.container}>
                <TouchableWithoutFeedback onPress={()=>{
                    back()
                }} >
                    <Text style={{marginLeft: 15, fontSize: 18}}>
                        取消
                    </Text>
                </TouchableWithoutFeedback>
                <View style={{flex: 1, alignItems: 'center', marginTop: 20,}}>
                    <View style={{flexDirection:'row',justifyContent:'center',overflow:'hidden',position:'relative',alignItems:'center', width: 240, height: 240, borderRadius: 120,borderWidth: 2,borderColor:'#409EFF'}}>
                        <Camera
                            ref={camara}
                            style={{width: faceWidthAndHeight, height: faceWidthAndHeight, borderRadius: 110,}}
                            device={device}
                            isActive={isActiveVal}
                            photo={true}
                            frameProcessor={frameProcessor}
                            frameProcessorFps={'auto'}
                        />
                        <Text style={{fontSize:16,color:'#fff',fontWeight:'500',position:'absolute',top:195,textAlign:'center'}}>{msg}</Text>
                        <View style={{backgroundColor:'#000',opacity:0.1,position:'absolute',width:220,top:190, height:60}}>
                        </View>
                    </View>
                    <View style={{marginTop:15}}>
                        <Text style={{fontSize:20,fontWeight:'400'}}>{uploadMsg}</Text>
                    </View>
                </View>

            </View>
        </SafeAreaView>
    ) : null;
}

